﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace WebAdmin.JWT
{
    /// <summary>
    /// 权限过滤
    /// </summary>
    public class PermissionRequirement : IAuthorizationRequirement
    {

    }

    /// <summary>
    /// 权限过滤
    /// </summary>
    public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
    {
        private IHttpContextAccessor _Accessor;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        public PermissionHandler(IHttpContextAccessor Accessor)
        {
            this._Accessor = Accessor;
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            var httpContext = this._Accessor.HttpContext;
            var isAuthenticated = httpContext != null && httpContext.User.Identity.IsAuthenticated;
            if (isAuthenticated)
            {
                var UserID = httpContext.User.Claims.SingleOrDefault(m => m.Type == ClaimTypes.UserData)?.Value;
                if (!string.IsNullOrWhiteSpace(UserID))
                    context.Succeed(requirement);
                else
                    context.Fail();
            }
            return Task.CompletedTask;
        }
    }
}
